package com.ltkj.baseplatform.service.impl;

import com.ltkj.baseplatform.domain.*;
import com.ltkj.baseplatform.domain.bo.ArtContentBo;
import com.ltkj.baseplatform.domain.bo.ArtContentQueryBo;
import com.ltkj.baseplatform.domain.vo.ArtContentVo;
import com.ltkj.baseplatform.domain.vo.SerCollectDataVo;
import com.ltkj.baseplatform.mapper.*;
import com.ltkj.baseplatform.service.IArtContentService;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.system.api.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文章内容Service业务层处理
 * 
 * @author liupf
 * @date 2023-08-28
 */
@Service
public class ArtContentServiceImpl implements IArtContentService 
{
    @Autowired
    private ArtContentMapper artContentMapper;
    @Autowired
    private ArtContentBusinessMapper artContentBusinessMapper;
    @Autowired
    private ArtCollectionBusinessMapper artCollectionBusinessMapper;
    @Autowired
    private RedisService redisService;

    @Autowired
    private SerCollectDataMapper serCollectDataMapper;

    @Autowired
    private SerCommentDataMapper serCommentDataMapper;

    @Autowired
    private SerLikesDataMapper serLikesDataMapper;

    /**
     * 查询文章内容
     * 
     * @param id 文章内容主键
     * @return 文章内容
     */
    @Override
    public ArtContentVo selectArtContentById(Long id)
    {
        ArtContentVo artContentVo = artContentBusinessMapper.selectArtContentById(id);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long currUserId = loginUser != null ? loginUser.getUserid() : null;
        //登录内显示是否点赞或者收藏
        if(currUserId != null){
            //查询当前用户是否收藏
            SerCollectData serCollectData = new SerCollectData();
            serCollectData.setBizId(id);
            serCollectData.setTypeCode("article");
            serCollectData.setUserId(currUserId);
            int count = serCollectDataMapper.selectCountByOptions(serCollectData);
            if(count > 0){
                artContentVo.setHasCollect(true);
            }
            //查询当前用户是否点赞
            SerLikesData serLikesData = new SerLikesData();
            serLikesData.setBizId(id);
            serLikesData.setTypeCode("article");
            serLikesData.setUserId(currUserId);
            int likeCount = serLikesDataMapper.selectCountByOptions(serLikesData);
            if(likeCount > 0){
                artContentVo.setHasLikes(true);
            }
        }
        return artContentVo;
    }
    /**
     * 查询文章内容
     *
     * @param id 文章内容主键
     * @return 文章内容
     */
    @Override
    public ArtContent selectContentById(Long id)
    {
        return artContentMapper.selectArtContentById(id);
    }

    /**
     * 查询文章内容列表
     * 
     * @param artContent 文章内容
     * @return 文章内容
     */
    @Override
    public List<ArtContent> selectArtContentList(ArtContent artContent)
    {
        return artContentMapper.selectArtContentList(artContent);
    }

    /**
     * 新增文章内容
     * 
     * @param artContentBo 文章内容
     * @return 结果
     */
    @Override
    public int insertArtContent(ArtContentBo artContentBo)
    {
        ArtContent artContent = new ArtContent();
        BeanUtils.copyProperties(artContentBo,artContent);
        artContent.setCreateTime(DateUtils.getNowDate());
        artContent.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        validEntityBeforeSave(artContent);
        int i = artContentMapper.insertArtContent(artContent);
        //添加成功就移除缓存，首页使用
        if (i > 0){
            //首页内容缓存
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
        }
        return i;
    }

    /**
     * 修改文章内容
     * 
     * @param artContentBo 文章内容
     * @return 结果
     */
    @Override
    @Transactional
    public int updateArtContent(ArtContentBo artContentBo)
    {
        ArtContent artContent = new ArtContent();
        BeanUtils.copyProperties(artContentBo,artContent);
        artContent.setUpdateTime(DateUtils.getNowDate());
        artContent.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        validEntityBeforeEdit(artContent);
        int i = artContentMapper.updateArtContent(artContent);
        //修改成功就移除缓存，首页使用
        if (i > 0){
            //首页内容缓存
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
            SerCollectData serCollectData = new SerCollectData();
            serCollectData.setBizId(artContent.getId());
            serCollectData.setTypeCode("article");
            //设置一些文章的属性
            serCollectData.setAddr(artContent.getPlaceName());
            serCollectData.setViewNum(artContent.getReadNum());
            serCollectData.setImgPath(StringUtils.hasText(artContent.getCoverImgPath()) ? artContent.getCoverImgPath() : artContent.getImgPath());
            serCollectData.setTitle(artContent.getTitle());
            serCollectData.setLatitude(artContent.getLatitude());
            serCollectData.setLongitude(artContent.getLongitude());
            serCollectData.setIsDel(artContent.getIsDel());
            serCollectDataMapper.updateDelFlagByBizCode(serCollectData);
        }
        return i;
    }

    /**
     * 批量删除文章内容
     * 
     * @param ids 需要删除的文章内容主键
     * @return 结果
     */
    @Override
    public int deleteArtContentByIds(Long[] ids)
    {
        //return artContentMapper.deleteArtContentByIds(ids);
        int i = artContentBusinessMapper.recycle(ids);
        //删除成功就移除缓存，首页使用
        if (i > 0){
            //首页内容缓存
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
        }
        return i;
    }

    /**
     * 删除文章内容信息
     * 
     * @param id 文章内容主键
     * @return 结果
     */
    @Override
    public int deleteArtContentById(Long id)
    {
        int i = artContentMapper.deleteArtContentById(id);
        //删除成功就移除缓存，首页使用
        if (i > 0){
            //首页内容缓存
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
        }
        return i;
    }

    /**
     * 将传入的文章数据放入回收站
     *
     * @param ids id集合
     * @return 结果
     */
    @Transactional
    @Override
    public int recycle(Long[] ids, List<ArtContent> list) {
        int result = artContentBusinessMapper.recycle(ids);
        String userName = SecurityUtils.getLoginUser().getUsername();
        Date nowDate = DateUtils.getNowDate();
        List<ArtCollection> collections = new ArrayList<>();
        //将数据放到回收站表
        for (ArtContent content : list) {
            ArtCollection collection = new ArtCollection();
            collection.setContentId(content.getId());
            collection.setCollectName(content.getTitle());
            collection.setType("1");
            collection.setIsDel("0");
            collection.setCreateBy(userName);
            collection.setCreateTime(nowDate);
            collections.add(collection);
        }
        if(!CollectionUtils.isEmpty(collections)){
            artCollectionBusinessMapper.insertBatch(collections);
        }
        //删除成功就移除缓存，首页使用
        if (result > 0){
            //首页内容缓存
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
            SerCollectData serCollectData = null;
            //批量删除的数据不会很多
            for (Long id : ids) {
                serCollectData = new SerCollectData();
                serCollectData.setBizId(id);
                serCollectData.setIsDel("2");
                serCollectData.setTypeCode("article");
                serCollectDataMapper.updateDelFlagByBizCode(serCollectData);
            }
        }
        return result;
    }
    /**
     * 根据id集合查询文章列表
     *
     * @param ids 文章id集合
     * @return 文章管理-文章集合
     */
    @Override
    public List<ArtContent> selectArtContentListByIds(Long[] ids) {
        return artContentBusinessMapper.selectArtContentListByIds(ids);
    }
    /**
     * 使用查询参数查询文章管理-文章列表
     *
     * @param artContentQueryBo 查询参数
     * @return 文章管理-文章集合
     */
    @Override
    public List<ArtContentVo> selectArtContentList(ArtContentQueryBo artContentQueryBo) {
        return artContentBusinessMapper.selectArtContentList(artContentQueryBo);
    }

    @Override
    public List<ArtContentVo> selectSubChannelContentList(ArtContentQueryBo artContentQueryBo) {
        return artContentBusinessMapper.selectSubChannelContentList(artContentQueryBo);
    }
    /**
     * 更新内容的浏览量+1
     *
     * @param id 内容id
     * @return 结果
     */
    @Override
    public int updateReadNum(Long id) {
        return artContentBusinessMapper.updateReadNum(id);
    }
    /**
     * 更新内容的评论量
     *
     * @param id 内容id
     * @return 结果
     */
    @Override
    public int updateCommentNum(Integer num, Long id) {
        return artContentBusinessMapper.updateCommentNum(num,id);
    }
    /**
     * 更新内容的收藏量
     *
     * @param id 内容id
     * @return 结果
     */
    @Override
    public int updateCollectNum(Integer num, Long id) {
        return artContentBusinessMapper.updateCollectNum(num,id);
    }
    /**
     * 更新内容的点赞量
     *
     * @param id 内容id
     * @return 结果
     */
    @Override
    public int updateLikeNum(Integer num, Long id) {
        return artContentBusinessMapper.updateLikeNum(num,id);
    }


    //游记点赞
    @Override
    @Transactional
    public int addLikes(Long id) {
        SerLikesData serLikesData = new SerLikesData();
        serLikesData.setBizId(id);
        serLikesData.setTypeCode("article");
        serLikesData.setUserId(SecurityUtils.getLoginUser().getUserid());
        serLikesData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serLikesData.setCreateTime(DateUtils.getNowDate());
        int num = serLikesDataMapper.insertSerLikesData(serLikesData);
        if(num > 0){
            artContentBusinessMapper.updateLikeNum(1,id);
        }
        return num;
    }
    //游记取消点赞
    @Override
    @Transactional
    public int cancelLikes(Long id) {
        int num = serLikesDataMapper.deleteLikesDataByBizIdAndCode(id, "article");
        if(num > 0){
            artContentBusinessMapper.updateLikeNum(-1,id);
        }
        return num;
    }

    @Override
    @Transactional
    public int addCollect(SerCollectData serCollectData) {
        if(serCollectData.getBizId() == null){
            throw new ServiceException("请输入业务编号！");
        }
        ArtContent artContent = artContentMapper.selectArtContentById(serCollectData.getBizId());
        if(artContent == null){
            throw new ServiceException("文章数据不存在！");
        }
        serCollectData.setTypeCode("article");
        serCollectData.setUserId(SecurityUtils.getLoginUser().getUserid());
        serCollectData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serCollectData.setCreateTime(DateUtils.getNowDate());
        //设置一些文章的属性
        serCollectData.setAddr(artContent.getPlaceName());
        serCollectData.setViewNum(artContent.getReadNum());
        serCollectData.setImgPath(StringUtils.hasText(artContent.getCoverImgPath()) ? artContent.getCoverImgPath() : artContent.getImgPath());
        serCollectData.setTitle(artContent.getTitle());
        serCollectData.setLatitude(artContent.getLatitude());
        serCollectData.setLongitude(artContent.getLongitude());
        serCollectData.setIsDel(artContent.getIsDel());
        int num = serCollectDataMapper.insertSerCollectData(serCollectData);
        if(num > 0){
            //收藏量 +1
            artContentBusinessMapper.updateCollectNum(1,serCollectData.getBizId());
        }
        return num;
    }

    @Override
    @Transactional
    public int cancelColect(Long id) {
        int num = serCollectDataMapper.deleteCollectDataByBizIdAndCode(id, "article");
        if(num > 0){
            //评论量 -1
            artContentBusinessMapper.updateCollectNum(-1,id);
        }
        return num;
    }

    @Override
    @Transactional
    public int publishComment(SerCommentData serCommentData) {
        if(serCommentData.getBizId() == null){
            throw new ServiceException("请输入业务编号！");
        }
        serCommentData.setTypeCode("article");
        serCommentData.setUserId(SecurityUtils.getLoginUser().getUserid());
        serCommentData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serCommentData.setCreateTime(DateUtils.getNowDate());
        int num = serCommentDataMapper.insertSerCommentData(serCommentData);
        if(num > 0){
            //评论量 +1
            artContentBusinessMapper.updateCommentNum(1,serCommentData.getBizId());
        }
        return num;
    }

    @Override
    @Transactional
    public int deleteComment(Long id) {
        SerCommentData serCommentData = serCommentDataMapper.selectSerCommentDataById(id);
        int num = serCommentDataMapper.deleteSerCommentDataById(id);
        if(num > 0){
            //评论量 -1
            artContentBusinessMapper.updateCommentNum(-1,serCommentData.getBizId());
        }
        return num;
    }

    @Override
    public List<SerCollectDataVo> selectSerCollectDataList() {
        SerCollectData serCollectData = new SerCollectData();
        serCollectData.setUserId(SecurityUtils.getLoginUser().getUserid());
        return serCollectDataMapper.selectSerCollectDataList(serCollectData);
    }

    /**
     * 新增数据前的数据校验
     */
    private void validEntityBeforeSave(ArtContent entity){

    }

    /**
     * 编辑数据前的数据校验
     */
    private void validEntityBeforeEdit(ArtContent entity){

    }
}
